import {
  getCardList
} from "../../apis/card";
import {
  notice
} from '../../apis/group';
import {
  globalData
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    titleTop: 0,
    titleHeight: 0,
    historyList: [],
    defaultCard: {},
    cardTotal: 0,
    shareImage: ''
  },

  onLoad() {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      titleTop: menu.top + 2,
      titleHeight: menu.height
    });
  },

  onShow() {
    this.setData({
      showGroupBtn: globalData.checkIn
    });
    wx.getStorage({
      key: 'historyPreview',
      success: res => {
        let arr = JSON.parse(res.data);
        this.setData({
          historyList: arr
        });
      },
      fail: res => {}
    });
    this.getMyCard();
    this.getNotice();
  },

  onShareAppMessage() {
    if (this.data.cardTotal === 0) {
      return {
        title: '加入快名片',
        path: `/pages/start/index`,
        imageUrl: '/images/fastCard.png'
      }
    } else {
      return {
        title: this.data.defaultCard.userName + '的快名片',
        path: `/pages/cardPreview/index?type=share&cardId=${this.data.defaultCard.cardId}`,
        imageUrl: this.data.shareImage
      }
    };
  },

  getMyCard() {
    getCardList({
      cardType: 1
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        this.setData({
          cardTotal: total
        });
        if (total === 1) {
          this.setData({
            defaultCard: rows[0],
            cardTotal: total
          });
        } else if (total > 1) {
          this.setData({
            defaultCard: rows.find(v => {
              return v.isDefault === 1
            }) ? rows.find(v => {
              return v.isDefault === 1
            }) : rows[0]
          });
        };
        if (this.data.defaultCard.avatar) {
          wx.getImageInfo({
            src: !new RegExp('https://').test(this.data.defaultCard.avatar) && !new RegExp('http://').test(this.data.defaultCard.avatar) ? app.globalData.url + this.data.defaultCard.avatar : this.data.defaultCard.avatar,
            success: res => {
              let avatar = {
                path: res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, this.data.defaultCard.userName, this.data.defaultCard.company, this.data.defaultCard.post, this.data.defaultCard.label);
            }
          });
        };
      };
    });
  },

  getNotice() {
    notice().then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        for (let key in data) {
          if (data[key] !== 0) wx.showTabBarRedDot({
            index: 2
          });
        };
      };
    });
  },

  // 生成分享小卡片
  canvasShareImage(avatar, userName, company, post, label) {
    let cvs = wx.createCanvasContext('share');
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 70, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 16, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 16, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 16, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(26);
    let nameWidth = cvs.measureText(userName).width;
    cvs.fillText(userName, 210 - nameWidth / 2, 164);

    cvs.setFillStyle('#f7f7f7');
    cvs.setFontSize(20);
    let postWidth = cvs.measureText(`${company} · ${post}`).width;
    cvs.fillText(`${company} · ${post}`, 210 - postWidth / 2, 200);

    if (label.length > 0) {
      cvs.setFillStyle('#fff');
      cvs.setFontSize(22);
      label = label.map(v => {
        return {
          labelName: '#' + v,
          labelWidth: cvs.measureText('#' + v).width
        }
      }).sort((a, b) => b.labelWidth - a.labelWidth);
      let lineWidth = cvs.measureText('　|　').width;
      switch (label.length) {
        case 1:
          cvs.fillText(label[0].labelName, 210 - label[0].labelWidth / 2, 260);
          break;
        case 2:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          break;
        case 3:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName, 210 - (label[2].labelWidth) / 2, 300);
          break;
        case 4:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + lineWidth) / 2, 300);
          break;
        case 5:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName + '　|　' + label[4].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + label[4].labelWidth + lineWidth * 2) / 2, 300);
          break;
        default:
          break;
      };
    };

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            shareImage: res.tempFilePath
          });
        }
      });
    });
  },

  // 我的名片
  goMyCard() {
    wx.navigateTo({
      url: '/pages/myCard/index'
    });
  },

  // 名片码
  goQRcode() {
    if (this.data.cardTotal === 0) {
      wx.showToast({
        title: '您还没有名片',
        icon: 'none'
      });
    } else {
      wx.navigateTo({
        url: `/pages/qrCode/index?type=card&cardId=${this.data.defaultCard.cardId}`
      });
    };
  },

  // 建群
  goCreateGroup() {
    if (this.data.cardTotal === 1) {
      wx.navigateTo({
        url: `/pages/createGroup/index?type=createGroup&cardId=${this.data.defaultCard.cardId}`
      });
    } else {
      wx.navigateTo({
        url: '/pages/myCard/index?type=createGroup'
      });
    };
  },

  // 发名片
  sendCard() {
    wx.navigateTo({
      url: '/pages/myCard/index?type=share',
    });
  },

  // 清除历史
  removeHistory() {
    wx.showModal({
      title: '确定清除最近浏览？',
      success: res => {
        if (res.confirm) {
          this.setData({
            historyList: []
          });
          wx.removeStorage({
            key: 'historyPreview',
            success: res => {
              wx.showToast({
                title: '清除成功',
                icon: 'success'
              });
            }
          });
        };
      }
    });
  },

  previewCard(e) {
    let {
      index
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/groupCardPreview/index?type=history&current=${index}`
    });
  }
})